# coding=utf-8
import urllib2
import os
import sys
import time
import re
import json
import progressbar

from selenium import webdriver
from image_handler import ImageHandler

browser = webdriver.PhantomJS()

base_url = 'http://www.930mh.com/'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Safari/604.1.38'}


def main():
    if len(sys.argv) < 2:
        print 'please specify page'
        return

    url = base_url + 'manhua/' + sys.argv[1] + '/'
    print 'retrieving page:' + url

    browser.get(url)
    ul = browser.find_element_by_id('chapter-list-1')
    lis = ul.find_elements_by_tag_name('li')

    chapter_infos = {}

    for li in lis:
        chapter_infos[li.find_element_by_class_name('list_con_zj').get_property('text')] = li.find_element_by_tag_name(
            'a').get_attribute('href')

    for key in sorted(chapter_infos.keys()):
        print 'start to save chapter ' + key

        if not os.path.exists(key):
            os.makedirs(key)
        else:
            print 'already exists'
            continue

        time.sleep(2)

        request = urllib2.Request(url=chapter_infos.get(key), headers=headers)
        html = urllib2.urlopen(request).read()

        pattern = re.compile(r'<script>;var chapterImages = (.*);var chapterPath', re.I)
        urls = pattern.findall(html)
        url = urls[0]
        json_array = json.loads(url)

        pattern = re.compile(r'var chapterPath = "(.*)";var pageTitle', re.I)
        prefixes = pattern.findall(html)
        prefix = prefixes[0]

        bar = progressbar.ProgressBar()

        for i in bar(range(len(json_array))):
            image_url = 'http://mhimg.930mh.com:22122/' + prefix + json_array[i]
            ImageHandler.save_image(file_path=u'{0}/{1}.jpg'.format(key, i), image_url=image_url)

            time.sleep(1)

        print '\nsave chapter finish'


if __name__ == '__main__':
    main()
